package App.Controller;

import App.Model.Upload.UploadFileResponse;
import App.Service.TaskService;
import App.Utility.CommonHelper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by xw on 2018/12/12.
 */

@RestController
@RequestMapping("/api/file/")
public class FileController extends BaseController {

    @Autowired
    private TaskService _service;

    @Autowired
    private CommonHelper _commonHelper;

    @RequestMapping(value = "upload")
    @ResponseBody
    public ResponseEntity<?> uploadFile(@RequestParam(value = "file", required = true) MultipartFile file) throws IOException {

        UploadFileResponse _response = new UploadFileResponse();
        String _filePath = _commonHelper.getUploadFilePath();

        String _fileid = UUID.randomUUID().toString();
        String _oldFileName = file.getOriginalFilename();
        String _fileSuffix = FilenameUtils.getExtension(_oldFileName);
        String _baseFileName = FilenameUtils.getBaseName(_oldFileName);

        String _fileName = "";

        String _showName = "";
        Date _now = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        if (!_fileSuffix.isEmpty()) {
            _showName = sdf.format(_now) + "." + _fileSuffix;
            _fileName = _fileid + "." + _fileSuffix;
        } else {
            _showName = sdf.format(_now);
            _fileName = _fileid;
        }

        byte[] bytes = file.getBytes();
        File fileToSave = new File(_filePath + _fileName);
        FileCopyUtils.copy(bytes, fileToSave);
        _service.insertFileUploadRecord(_fileid, _oldFileName, _fileName, _showName, _fileSuffix, userId());

        _response.setFileid(_fileid);
        _response.setNewfilename(_fileName);
        _response.setOldfilename(_oldFileName);
        _response.setShowfilename(_showName);
        _response.setExtension(_fileSuffix);
        _response.setIssuccess(true);

        return new ResponseEntity(_response, HttpStatus.OK);
    }

    @RequestMapping(value = "uploadfiles", method = RequestMethod.POST)
    public ResponseEntity<?> multipleFileUpload(@RequestParam(value = "file", required = true) List<MultipartFile> _files) throws IOException {

        String _filePath =_commonHelper.getUploadFilePath();
        List<UploadFileResponse> _allResponse = new ArrayList<>();
        for (MultipartFile file : _files) {

            String _fileid = UUID.randomUUID().toString();
            String _oldFileName = file.getOriginalFilename();
            String _fileSuffix = FilenameUtils.getExtension(_oldFileName);
            String _fileName = _fileid + "." + _fileSuffix;

            String _showName = "";
            Date _now = new Date();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            if (!_fileSuffix.isEmpty()) {
                _showName = sdf.format(_now) + "." + _fileSuffix;
                _fileName = _fileid + "." + _fileSuffix;

            } else {
                _showName = sdf.format(_now);
                _fileName = _fileid;
            }
            if (!file.isEmpty()) {
                byte[] bytes = file.getBytes();
                File fileToSave = new File(_filePath + _fileName);
                FileCopyUtils.copy(bytes, fileToSave);

                _service.insertFileUploadRecord(_fileid, _oldFileName, _fileName, _showName, _fileSuffix, userId());
            }

            UploadFileResponse _response = new UploadFileResponse();
            _response.setFileid(_fileid);
            _response.setNewfilename(_fileName);
            _response.setOldfilename(_oldFileName);
            _response.setShowfilename(_showName);
            _response.setExtension(_fileSuffix);

            _allResponse.add(_response);
        }
        return new ResponseEntity(_allResponse, HttpStatus.OK);
    }


    @GetMapping(value = "download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "lifa.exe";// 文件名
        if (fileName != null) {
            //设置文件路径
            File file = new File("/data/approot/uploads/lifa1.0.1.exe");
//
//            File file = new File(realPath , fileName);


            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {

                System.out.println("file not exists");
            }
        }
        return "下载失败";
    }


    @RequestMapping(value = "uploadbatch", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseEntity<?> getFile(HttpServletRequest request) throws Exception {

        String _taskid = request.getParameter("taskid");
        String _filePath =_commonHelper.getUploadFilePath();

        List<UploadFileResponse> _allResponse = new ArrayList<>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        for (String key : fileMap.keySet()) {

            UploadFileResponse _response = new UploadFileResponse();

            try {
                MultipartFile file = fileMap.get(key);
                String req = file.getOriginalFilename();
                if (req.isEmpty()) {
                    continue;
                }

                String _fileid = key; //UUID.randomUUID().toString();
                String _oldFileName = file.getOriginalFilename();
                String _fileSuffix = FilenameUtils.getExtension(_oldFileName);
                String _fileName = _fileid + "." + _fileSuffix;

                String _showName = "";
                Date _now = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");

                if (!_fileSuffix.isEmpty()) {
                    _showName = sdf.format(_now) + "." + _fileSuffix;
                    _fileName = _fileid + "." + _fileSuffix;

                } else {
                    _showName = sdf.format(_now);
                    _fileName = _fileid;
                }
                if (!file.isEmpty()) {
                    byte[] bytes = file.getBytes();
                    File fileToSave = new File(_filePath + _fileName);
                    FileCopyUtils.copy(bytes, fileToSave);
                    _service.insertFileUploadRecord(_fileid, _oldFileName, _fileName, _showName, _fileSuffix, userId());
                }

                _response.setFileid(_fileid);
                _response.setNewfilename(_fileName);
                _response.setOldfilename(_oldFileName);
                _response.setShowfilename(_showName);
                _response.setExtension(_fileSuffix);
                _response.setIssuccess(true);

            } catch (Exception ex) {
                _response.setIssuccess(false);
                ex.printStackTrace();
            }
            _allResponse.add(_response);

        }

        return new ResponseEntity(_allResponse, HttpStatus.OK);
    }


    /**
     * 下边这个是好方法
     **/

    public File getTmpFile(String fileName) {
        File tmpDir = FileUtils.getTempDirectory();
        String tmpFileName = (Math.random() * 10000 + "").replace(".", "") + "_" + fileName;
        return new File(tmpDir, tmpFileName);
    }

}